import pymysql


class Util:
    # 初始化链接和游标对象
    __connect = None
    __course = None

    # 创建连接
    @classmethod
    def __create_line(cls):
        if cls.__connect is None:
            cls.__connect = pymysql.connect(host='localhost', port=3306, user='root', password='root', database='books',
                                            autocommit=False)
        return cls.__connect

    # 创建游标
    @classmethod
    def __create_course(cls):
        if cls.__course is None:
            cls.__course = cls.__create_line().cursor()
        return cls.__course

    # 执行sql
    @classmethod
    def execute_sql(cls, sql):
        try:
            course = cls.__create_course()
            course.execute(sql)
            if sql.split()[0].lower() == 'select':
                return course.fetchall()
            else:
                cls.__create_line().commit()
                return course.rowcount
        except Exception as a:
            cls.__create_line().rollback()
            print(a)
        finally:
            cls.__close_course()
            cls.__close_line()

    # 关闭游标
    @classmethod
    def __close_course(cls):
        if cls.__course:
            cls.__course.close()
            cls.__course = None

    # 关闭连接
    @classmethod
    def __close_line(cls):
        if cls.__connect:
            cls.__connect.close()
            cls.__connect = None
